﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Web;
using System.Linq;
using SlamCms.SharePoint.Core;
using SlamCms.Data;
using System.Collections.Generic;
using SlamCms.Common;
using System.Data;
using System.IO;
using SlamCms.Configuration;

namespace SlamCms.SharePoint.Publishing.WebParts
{
    public partial class ExpiringContentControl : UserControl
    {

        public int PageSize { get; set; }

        public int DaysScope { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptInclude("jquery", ResolveUrl("~/_layouts/inc/jquery-1.6.2.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("datatables", ResolveUrl("~/_layouts/inc/jquery.dataTables.js"));
			Page.ClientScript.RegisterClientScriptInclude("datatablesplugins", ResolveUrl("~/_layouts/inc/dataTables.plugins.js"));
            AddCssInclude("/Style Library/SlamCMS/css/SlamCMS_table.css");

			if (!IsPostBack)
			{
				ltSetKey.Text = DateTime.Now.Ticks.ToString();
			}
            this.ltDaysScope.Text = DaysScope.ToString();
            this.ltPageSize.Text = PageSize.ToString();

            if (ContentExists())
                this.ltInitScript.Text = GetInitScript();
            else 
                this.ltInitScript.Text = GetHideWebPartScript();
        }


        private bool ContentExists()
        {
			return GetContentQuery().Count() > 0;
        }


		private QueryBuilder GetContentQuery()
		{
			QueryBuilder builder = SlamCmsContext.Data.CreateQuery().FilterStatus(FilterStatus.Live);
			if (SlamCmsContext.User != null)
			{
				if (SlamCmsContext.User.Groups != null && SlamCmsContext.User.Groups.Count > 0)
				{
					var groups = (from g in SlamCmsContext.User.Groups where g.Edit select g).ToList();

					if (groups != null && groups.Count > 0)
					{
						List<Guid> siteIds = new List<Guid>();
						foreach (SlamCms.Data.Group g in groups)
						{
							if (g.Sites != null)
								siteIds.AddRange(g.Sites.Select(id => id.SiteId));
						}

						var dateNow = DateTime.Today;
						var dateScope = dateNow.AddDays(this.DaysScope);

						builder = builder.FilterSite(siteIds)
							.Filter("ContentItem.ExpirationDate IS NOT NULL {1}and ContentItem.ExpirationDate < '{0}'".F(dateScope.ToString("MM/dd/yyyy"), !includeExpiredContentCheckBox.Checked ? "and ContentItem.ExpirationDate >= '" + dateNow.ToString("MM/dd/yyyy") + "' " : ""))
							.Cache(QueryCacheBehavior.NoCache);
					}
				}
			}

			return builder;
		}

        private string GetInitScript()
        {
            string userName = HttpContext.Current.User.Identity.Name.Contains("|") ? HttpContext.Current.User.Identity.Name.Split('|').Last() : HttpContext.Current.User.Identity.Name;

            StringBuilder builder = new StringBuilder("");
            builder.Append("<script type=\"text/javascript\">");
            string varName = "expiringContent_" + this.ClientID;
            builder.AppendLine(String.Format("var {0} = new Control('{1}','{2}','{3}')", varName, settingsContainer.ClientID, controlsContainer.ClientID, userName.Replace("\\","\\\\")));
            builder.AppendLine("$(document).ready(" + varName + ".documentReady());");
            builder.Append("</script>");

            return builder.ToString();
        }

        private string GetHideWebPartScript()
        { 
           StringBuilder builder = new StringBuilder("");
           builder.Append("<script type=\"text/javascript\">");
           string script = String.Format("$('#{0}').parent().parent().parent().parent().parent().parent().parent().hide();", controlsContainer.ClientID);
            builder.AppendLine("$(document).ready(function(){" + script + "});");
            builder.Append("</script>");
            return builder.ToString();
        }


        private void AddCssInclude(string url)
        {
            string include = String.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" media=\"all\" />", ResolveUrl(url));
            if (!Page.Header.Controls.Cast<Control>().OfType<LiteralControl>().Any(c => c.Text == include))
            {
                Page.Header.Controls.Add(new LiteralControl(include));
            }
        }

		protected void generateExcelLink_Click(object sender, EventArgs e)
		{
			exportContentGrid.Visible = true;
			string userName = HttpContext.Current.User.Identity.Name.Contains("|") ? HttpContext.Current.User.Identity.Name.Split('|').Last() : HttpContext.Current.User.Identity.Name;
			var resultContent = GetContentQuery().OrderBy("ExpirationDate asc").Get();

			DataTable contentTable = new DataTable();
			contentTable.Columns.Add(new DataColumn("ID", typeof(string)));
			contentTable.Columns.Add(new DataColumn("Expires", typeof(DateTime)));
			contentTable.Columns.Add(new DataColumn("Title", typeof(string)));
			contentTable.Columns.Add(new DataColumn("Site", typeof(string)));
			contentTable.Columns.Add(new DataColumn("Type", typeof(string)));
			contentTable.Columns.Add(new DataColumn("Created By", typeof(string)));
			contentTable.Columns.Add(new DataColumn("Created", typeof(DateTime)));
			contentTable.Columns.Add(new DataColumn("Link", typeof(string)));

			string applicationFrontEndUrl = ConfigurationManager.Environment.DefaultApplication.FrontEndUrl.TrimEnd('/');

			foreach (SlamCms.Data.ContentItem item in resultContent)
			{
				string zone = "";
				string siteTitle = "";

				if (item.List != null)
				{
					if (item.List.Site != null)
					{
						if (item.List.Site.Zones != null)
						{
							if (item.List.Site.Zones.Count() > 0)
								zone = item.List.Site.Zones.FirstOrDefault().Title;
						}
						siteTitle = item.List.Site.Title;
					}
				}

				DataRow newRow = contentTable.NewRow();
				newRow["ID"] = item.ContentItemId;
				newRow["Expires"] = item.ExpirationDate.Value;
				newRow["Title"] = item.ReferenceTitle;
				newRow["Link"] = applicationFrontEndUrl + "/link/" + item.ContentItemId.Replace("-p", String.Empty);
				newRow["Site"] = siteTitle;
				newRow["Type"] = item.ContentType.Title;
				newRow["Created By"] = item.CreatedByUser.Name;
				newRow["Created"] = item.CreatedDate;
				contentTable.Rows.Add(newRow);
			}

			exportContentGrid.DataSource = contentTable;
			exportContentGrid.DataBind();

			Response.Clear();
			Response.AddHeader("content-disposition", String.Format("attachment; filename=ExpiringContent.xls"));
			Response.ContentType = "application/ms-excel";

			using (StringWriter stringWriter = new StringWriter())
			{
				using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
				{
					Control gridParent = exportContentGrid.Parent;
					int gridControlIndex = 0;
					if (gridParent != null)
					{
						gridControlIndex = gridParent.Controls.IndexOf(exportContentGrid);
						gridParent.Controls.Remove(exportContentGrid);
					}
					exportContentGrid.RenderControl(htmlWriter);
					if (gridParent != null)
						gridParent.Controls.AddAt(gridControlIndex, exportContentGrid);

					Response.Write(stringWriter.ToString());
					Response.End();
				}
			}
			exportContentGrid.Visible = false;
		}
    }
}
